package com.sky.common.util.helper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.cglib.beans.BeanCopier;

public class Beans {

	private static final Map<String, BeanCopier> BEAN_COPIERS = new ConcurrentHashMap<String, BeanCopier>();
	
	public static BeanHelper fromClz(Class<?> srcClazz, Class<?> destClazz){
		
		return new BeanHelper(genCopier(srcClazz, destClazz));
	}
	
	public static BeanHelper fromObj(Object srcObj,Object tarObj){
		
		return new BeanHelper(genCopier(srcObj.getClass(), tarObj.getClass())).srcObj(srcObj).tarObj(tarObj);
	}
	
	private static BeanCopier genCopier(Class<?> srcClazz, Class<?> destClazz) {

		String key = genKey(srcClazz, destClazz);

		BeanCopier copier = null;
		
		if (!BEAN_COPIERS.containsKey(key)) {
			
			copier = BeanCopier.create(srcClazz, destClazz,false);
			BEAN_COPIERS.put(key, copier);
			
		} else {
			
			copier = BEAN_COPIERS.get(key);
		}
		
		return copier;
	}

	private static String genKey(Class<?> srcClazz, Class<?> destClazz) {

		return srcClazz.getName() + destClazz.getName();
	}

	public static class BeanHelper {

		private BeanCopier copier;
		
		private Object srcObj;
		
		private Object tarObj;

		public BeanHelper(BeanCopier copier) {

			this.copier = copier;
		}
		
		public BeanHelper srcObj(Object srcObj){
			
			this.srcObj = srcObj;
			return this;
		}
		
		public BeanHelper tarObj(Object tarObj){
			
			this.tarObj = tarObj;
			return this;
		}

		public void copy(Object source, Object target) {

			copier.copy(source, target, null);
		}
		
		public void copy(){
			
			if(srcObj == null || tarObj == null){
				
				return;
			}
			
			copier.copy(srcObj, tarObj, null);
		}

	}

}
